package com.dswz.controller.admin;

import com.dswz.po.Goods;
import com.dswz.service.GoodsService;
import com.dswz.service.SessionService;
import com.dswz.service.UploadService;
import com.dswz.utils.AdminResult;
import com.dswz.utils.DateUtil;
import com.dswz.utils.PageBean;
import com.dswz.utils.RequestUtils;
import com.dswz.utils.Utils;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping({ "/admins" })
public class GoodsAdminController {
	private Logger logger = LogManager.getLogger(GoodsAdminController.class);

	@Autowired
	private GoodsService goodsService;

	@Autowired
	private SessionService sessionService;

	@Autowired
	private UploadService uploadService;

	@RequestMapping(value = { "/getGoodsList" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	@ResponseBody
	public Object getGoodsList(Byte goodsType, String goodsTitle, String goodsCreateTime, Integer page, Integer rows,
			Model model, HttpServletRequest request, HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		AdminResult result = new AdminResult();
		try {
			String username = this.sessionService.getAttibute(RequestUtils.getCSESSIONID(request, response),
					"ADMIN_SESSION");
			this.logger.info("goodsType:" + goodsType + "goodsTitle:" + goodsTitle + "goodsCreateTime:"
					+ goodsCreateTime + "page:" + page + "limit:" + rows + "页面来源:" + request.getHeader("referer")
					+ "客户端:" + request.getHeader("user-agent") + " 客户端ip: " + Utils.getUserRealAddress(request)
					+ " 操作人: " + username);
			PageBean pb = this.goodsService.getGoodsList(username, goodsType, goodsTitle, goodsCreateTime,
					Byte.valueOf((byte) 0), page, rows);
			result.setResult(0);
			result.setMessage("OK");
			result.setRows(pb.getContentList());
			result.setTotal(pb.getTotalRecords());
			long endTime = System.currentTimeMillis();
			this.logger.info("result:" + new Gson().toJson(result) + "程序运行时间" + (endTime - startTime) + "ms");
		} catch (Exception e) {
			result.setResult(2);
			result.setMessage(e.getMessage());
			this.logger.error(e.getMessage(), e);
		}
		return result;
	}

	@RequestMapping(value = { "/editGoods" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
	@ResponseBody
	public Object editGoods(String goodsId, Model model, HttpServletRequest request, HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		AdminResult result = new AdminResult();
		try {
			String username = this.sessionService.getAttibute(RequestUtils.getCSESSIONID(request, response),
					"ADMIN_SESSION");
			this.logger.info("goodsId:" + goodsId + "页面来源:" + request.getHeader("referer") + "客户端:"
					+ request.getHeader("user-agent") + " 客户端ip: " + Utils.getUserRealAddress(request) + " 操作人: "
					+ username);
			Goods goods = this.goodsService.getGoodsById(goodsId);
			result.setData(goods);
			result.setResult(0);
			result.setMessage("OK");
			long endTime = System.currentTimeMillis();
			this.logger.info("result:" + new Gson().toJson(result) + "程序运行时间" + (endTime - startTime) + "ms");
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
			result.setMessage(e.getMessage());
			result.setResult(2);
		}
		return result;
	}

	@RequestMapping(value = { "/saveEditGoods" }, method = {
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public Object saveEditGoods(String goodsId, Byte goodsType, String goodsTitle, String goodsPic, Double goodsPrice,
			String goodsDetail, Model model, HttpServletRequest request, HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		AdminResult result = new AdminResult();
		try {
			String username = this.sessionService.getAttibute(RequestUtils.getCSESSIONID(request, response),
					"ADMIN_SESSION");
			this.logger.info("goodsId:" + goodsId + "goodsType:" + goodsType + "goodsTitle:" + goodsTitle + "goodsPic:"
					+ goodsPic + "goodsPrice:" + goodsPrice + "goodsDetail:" + goodsDetail + "页面来源:"
					+ request.getHeader("referer") + "客户端:" + request.getHeader("user-agent") + " 客户端ip: "
					+ Utils.getUserRealAddress(request) + " 操作人: " + username);
			if (StringUtils.isEmpty(goodsId)) {
				this.logger.error("商品id为空!");
				result.setMessage("商品id为空!");
				result.setResult(3);
				return result;
			}
			if (goodsType == null) {
				this.logger.error("请选择商品类型!");
				result.setMessage("请选择商品类型!");
				result.setResult(3);
				return result;
			}
			if (StringUtils.isEmpty(goodsTitle)) {
				this.logger.error("请输入标题!");
				result.setMessage("请输入标题!");
				result.setResult(3);
				return result;
			}
			if (StringUtils.isEmpty(goodsPic)) {
				this.logger.error("图片地址为空!");
				result.setMessage("图片地址为空!");
				result.setResult(3);
				return result;
			}
			if (goodsPrice == null) {
				this.logger.error("价格为空!");
				result.setMessage("价格为空!");
				result.setResult(3);
				return result;
			}
			if (StringUtils.isEmpty(goodsDetail)) {
				this.logger.error("请输入商品详情!");
				result.setMessage("请输入商品详情!");
				result.setResult(3);
				return result;
			}
			Goods goods = new Goods();
			goods.setGoodsId(goodsId);
			goods.setGoodsType(goodsType);
			goods.setGoodsTitle(goodsTitle);
			goods.setGoodsPic(goodsPic);
			goods.setGoodsPrice(goodsPrice);
			goods.setGoodsDetail(goodsDetail);
			this.goodsService.updateGoods(goods);
			result.setResult(0);
			result.setMessage("OK");
			long endTime = System.currentTimeMillis();
			this.logger.info("result:" + new Gson().toJson(result) + "程序运行时间" + (endTime - startTime) + "ms");
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
			result.setMessage(e.getMessage());
			result.setResult(2);
		}
		return result;
	}

	@RequestMapping(value = { "/saveAddGoods" }, method = {
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public Object saveAddGoods(Byte goodsType, String goodsTitle, String goodsIntroduction, String goodsPic,
			Double goodsPrice, String goodsDetail, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		AdminResult result = new AdminResult();
		try {
			String username = this.sessionService.getAttibute(RequestUtils.getCSESSIONID(request, response),
					"ADMIN_SESSION");
			this.logger.info("goodsType:" + goodsType + "goodsTitle:" + goodsTitle + "goodsIntroduction:"
					+ goodsIntroduction + "goodsPic:" + goodsPic + "goodsPrice:" + goodsPrice + "goodsDetail:"
					+ goodsDetail + "页面来源:" + request.getHeader("referer") + "客户端:" + request.getHeader("user-agent")
					+ " 客户端ip: " + Utils.getUserRealAddress(request) + " 操作人: " + username);
			if (goodsType == null) {
				this.logger.error("请选择商品类型!");
				result.setMessage("请选择商品类型!");
				result.setResult(3);
				return result;
			}
			if (StringUtils.isEmpty(goodsTitle)) {
				this.logger.error("请输入标题!");
				result.setMessage("请输入标题!");
				result.setResult(3);
				return result;
			}
			if (StringUtils.isEmpty(goodsIntroduction)) {
				this.logger.error("请输入商品简介!");
				result.setMessage("请输入商品简介!");
				result.setResult(3);
				return result;
			}
			if (StringUtils.isEmpty(goodsPic)) {
				this.logger.error("图片地址为空!");
				result.setMessage("图片地址为空!");
				result.setResult(3);
				return result;
			}
			if (goodsPrice == null) {
				this.logger.error("价格为空!");
				result.setMessage("价格为空!");
				result.setResult(3);
				return result;
			}
			if (StringUtils.isEmpty(goodsDetail)) {
				this.logger.error("请输入商品详情!");
				result.setMessage("请输入商品详情!");
				result.setResult(3);
				return result;
			}
			Goods goods = new Goods();
			goods.setGoodsType(goodsType);
			goods.setGoodsTitle(goodsTitle);
			goods.setGoodsIntroduction(goodsIntroduction);
			goods.setGoodsPic(goodsPic);
			goods.setGoodsPrice(goodsPrice);
			goods.setGoodsDetail(goodsDetail);
			this.goodsService.insertGoods(goods);
			result.setResult(0);
			result.setMessage("OK");
			long endTime = System.currentTimeMillis();
			this.logger.info("result:" + new Gson().toJson(result) + "程序运行时间" + (endTime - startTime) + "ms");
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
			result.setMessage(e.getMessage());
			result.setResult(2);
		}
		return result;
	}

	@RequestMapping(value = { "/saveUploadGoodsImg" }, method = {
			org.springframework.web.bind.annotation.RequestMethod.POST })
	@ResponseBody
	public Object saveUploadGoodsImg(MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		AdminResult result = new AdminResult();
		try {
			String username = this.sessionService.getAttibute(RequestUtils.getCSESSIONID(request, response),
					"ADMIN_SESSION");
			this.logger.info("file.getOriginalFilename():" + file.getOriginalFilename() + "页面来源:"
					+ request.getHeader("referer") + "客户端:" + request.getHeader("user-agent") + " 客户端ip: "
					+ Utils.getUserRealAddress(request) + " 操作人: " + username);
			if (file.isEmpty()) {
				this.logger.error("图片为空!");
				result.setMessage("图片为空!");
				result.setResult(3);
				return result;
			}
			if (ImageIO.read(file.getInputStream()) == null) {
				this.logger.error("请上传图片");
				result.setMessage("请上传图片");
				result.setResult(3);
				return result;
			}
			String folder = "goods/" + username + "/" + DateUtil.format(new Date());
			String fn = file.getOriginalFilename();
			int pos = fn.lastIndexOf(".");
			String suffix = "";
			if (pos > 0) {
				suffix = fn.substring(pos);
			}
			if (StringUtils.isEmpty(suffix)) {
				suffix = ".jpg";
			}
			String url = this.uploadService.uploadFile(folder,
					DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + suffix, file);
			Map<String, String> map = new HashMap();
			map.put("imgUrl", url);
			result.setData(map);
			result.setResult(0);
			result.setMessage("OK");
			long endTime = System.currentTimeMillis();
			this.logger.info("result:" + new Gson().toJson(result) + "程序运行时间" + (endTime - startTime) + "ms");
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
			result.setResult(2);
			result.setMessage(e.getMessage());
		}
		return result;
	}

	@RequestMapping({ "/deleteGoodss" })
	@ResponseBody
	public Object deleteGoodss(String goodsIds, Model model, HttpServletRequest request, HttpServletResponse response) {
		long startTime = System.currentTimeMillis();
		AdminResult result = new AdminResult();
		try {
			String username = this.sessionService.getAttibute(RequestUtils.getCSESSIONID(request, response),
					"ADMIN_SESSION");
			this.logger.info("goodsIds:" + goodsIds + "页面来源:" + request.getHeader("referer") + "客户端:"
					+ request.getHeader("user-agent") + " 客户端ip: " + Utils.getUserRealAddress(request) + " 操作人: "
					+ username);
			List<String> list = new ArrayList();
			if (StringUtils.isEmpty(goodsIds)) {
				this.logger.error("请选择一个");
				result.setMessage("请选择一个");
				result.setResult(3);
				return result;
			}
			String[] goodsIdArr = goodsIds.split(",");
			String[] arrayOfString1;
			int j = (arrayOfString1 = goodsIdArr).length;
			for (int i = 0; i < j; i++) {
				String goodsId = arrayOfString1[i];
				list.add(goodsId);
			}
			this.goodsService.deleteGoodss(list);
			result.setResult(0);
			result.setMessage("OK");
			long endTime = System.currentTimeMillis();
			this.logger.info("result:" + new Gson().toJson(result) + "程序运行时间" + (endTime - startTime) + "ms");
		} catch (Exception e) {
			this.logger.error(e.getMessage(), e);
			result.setMessage(e.getMessage());
			result.setResult(2);
		}
		return result;
	}
}
